package com.mischa.doedeljas.server;

import com.mischa.doedeljas.Card;
import com.mischa.doedeljas.Card.Suit;

public class Trick 
{
	private Suit _trumpSuit;
	private int _startingPlayer;
	private int _nextPlayer;
	private boolean _isComplete = false;
	private Card[] cards = new Card[3];
	
	public Trick(Suit trumpSuit, int startingPlayer)
	{
		_trumpSuit = trumpSuit;
		_startingPlayer = startingPlayer;
		_nextPlayer = startingPlayer;
	}

	public void play(Card card)
	{
		cards[_nextPlayer] = card;
		
		_nextPlayer = (_nextPlayer + 1) % 3;
		
		if (_nextPlayer == _startingPlayer)
		{
			_isComplete = true;
			_nextPlayer = getLeader();
		}
	}
	
	private int getLeader()
	{		
		if (cards[(_startingPlayer + 1) % 3].exceeds(cards[_startingPlayer], _trumpSuit))
		{
			if (cards[(_startingPlayer + 2) % 3].exceeds(cards[(_startingPlayer + 1) % 3], _trumpSuit))
			{
				return (_startingPlayer + 2) % 3;
			}
			else
			{
				return (_startingPlayer + 1) % 3;
			}
		}
		else if (cards[(_startingPlayer + 2) % 3].exceeds(cards[(_startingPlayer + 1) % 3], _trumpSuit))
		{
			return (_startingPlayer + 2) % 3;
		}
		else
		{
			return _startingPlayer;
		}
	}
	
	public Card getCard(int player)
	{
		if (player >= 0 && player < 3)
		{
			return cards[player];					
		}
		else
		{
			return null;		
		}
	}
	
	public int getNextPlayer()
	{
		return _nextPlayer;
	}
	
	public boolean isComplete()
	{
		return _isComplete;
	}
	
}
